package com.andy.note.main.jsoup.gdhtcm;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import com.andy.note.boot.model.entity.doctor.DoctorInfo;

import cn.hutool.core.util.ReUtil;

/**
 * 
 * 爬取中医学院骨科所有医生
 *
 * @author Andy<908119428@qq.com>
 * @version $Revision: 1.1 $ $Date: 2021年7月29日 下午4:40:22 $
 */
public class GetDoctorInfo {

    private static final String WEBSITE_ENTER = "http://www.gdhtcm.com/sitecn/departmentsList.aspx?zkid=DK15";

    private static final String DOCTOR_DETAIL = "http://www.gdhtcm.com/sitecn/";


    public static void main(String[] args) throws Exception {


        // 1， 先获取所有骨科医生对应详细链接位置，并进行组装 对应地址 
        List<String> doctorList = getDoctorWebSite();

        // 2， 遍历所有地址， 判断是否为大德路医院，是则抽取对应数据
        List<DoctorInfo> result = new ArrayList<>();
        for (String doctorInfoUrl : doctorList) {
            Document document = Jsoup.connect(doctorInfoUrl).get();
            Elements c = document.getElementsByClass("expert_info");
            List<Node> child = c.get(0).childNodes();
            boolean isHospital = child.get(7).childNode(8).toString().contains("大德路");
            if(!isHospital) continue;
            String name = child.get(3).childNode(0).toString().split(" ")[0];
            String title = child.get(7).childNode(4).toString();
            String skill = child.get(7).childNode(12).toString();
            String description = child.get(7).childNode(14).toString();
            DoctorInfo doctorInfo = DoctorInfo.builder().doctorName(name).doctorTtitle(title).skill(skill).description(description).build();
            result.add(doctorInfo);
        }
        result.stream().forEach(System.out::println);
    }

    private static List<String> getDoctorWebSite() throws Exception {
        List<String> list = new ArrayList<>();
        // 正则 匹配所有医生的标签
        String regex = "<a href=\"ExpertInfoByDoctorID\\.aspx\\?id=\\w{4,5}\">([\\u4e00-\\u9fa5]{0,3})</a>";
        Document document = Jsoup.connect(WEBSITE_ENTER).get();

        // 获取所有a标签
        Elements a = document.getElementsByTag("a");

        // 匹配符合正则，含有医生名的连接，并且去掉前后标签
        for (Element e : a) {
            String context = e.toString();
            if(ReUtil.isMatch(regex, context)) {
                String href = e.attr("href");
                list.add(DOCTOR_DETAIL + href);
            }
        }
        list.stream().forEach(System.out::println);
        return list;
    }
}
